package com.fly.toolbox.component;

import com.fly.toolbox.bean.TaskInfo;
import com.fly.toolbox.config.ApplicationProperties;
import com.fly.toolbox.constant.BankEnum;
import com.fly.toolbox.service.NoteFileService;
import com.fly.toolbox.service.impl.NoteFileServiceImpl;
import com.fly.toolbox.util.DateUtils;
import com.intellij.openapi.fileEditor.FileEditorManager;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleUtilCore;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.roots.CompilerModuleExtension;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.ui.components.JBList;
import com.intellij.util.IconUtil;
import org.apache.commons.lang.StringUtils;
import org.jetbrains.annotations.NotNull;

import javax.swing.*;
import java.awt.*;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.nio.file.Path;
import java.util.Iterator;
import java.util.List;

public class FileSelectorComponent {
    private final ApplicationProperties properties = ApplicationProperties.getInstance();
    private final NoteFileService noteFileService = new NoteFileServiceImpl();

    private Project project;
    private final String id;
    private final JPanel panel;
    private final JBList<VirtualFile> fileList = new JBList<>();

    private final JButton resetButton = new CustomButtonRenderer("Reset");
    private final JButton deleteButton = new CustomButtonRenderer("Delete");
    private final JButton copyButton = new CustomButtonRenderer("Copy");
    private final JButton exportButton = new CustomButtonRenderer("Export");
    private final JButton importButton = new CustomButtonRenderer("Import");

    public FileSelectorComponent(Project project) {
        this.project = project;
        this.id = project.getBasePath();
        fileList.setModel(properties.getModel(project.getBasePath()));
        fileList.setCellRenderer(new RecentFileCellRenderer());

        // 创建工具栏
        JToolBar toolBar = new JToolBar();
        toolBar.setFloatable(false); // 设置工具栏不可拖动
        toolBar.setOpaque(false); // 设置工具栏透明
        toolBar.setBorder(BorderFactory.createEmptyBorder()); // 去除工具栏边框
        toolBar.setBorderPainted(false); // 去除工具栏边框绘制
        toolBar.add(Box.createHorizontalGlue()); // 将工具按钮放置在右侧

        toolBar.add(resetButton);
        toolBar.add(deleteButton);
        toolBar.add(copyButton);
        toolBar.add(exportButton);
        toolBar.add(importButton);

        resetButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                removeAll();
            }
        });
        deleteButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                removeSelectedIndices();
            }
        });
        copyButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                copyFiles();
                AppNotifier.notifyInfo("文件路径复制成功");
            }
        });
        exportButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String selectedOption = Messages.showEditableChooseDialog("导出到", "选择目录", Messages.getInformationIcon(), getExpDirAsArray(), DateUtils.getDate(), null);
                if (StringUtils.isNotEmpty(selectedOption)) {
                    exportFile(project, selectedOption);
                    Messages.showInfoMessage("文件导出成功", "Success");
                }
            }
        });
        importButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {

                ImportFileSelectorDialog dialog = new ImportFileSelectorDialog();
                dialog.show();

                if (dialog.isOK()) {
                    importFile(project, dialog.getText());
                }

            }
        });

        fileList.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (e.getClickCount() == 2) {  // 判断是否双击
                    int index = fileList.locationToIndex(e.getPoint());  // 获取双击位置的文件索引
                    if (index >= 0) {
                        VirtualFile file = fileList.getModel().getElementAt(index);  // 获取双击位置的文件
                        if (file != null && file.isValid()) {
                            FileEditorManager.getInstance(project).openFile(file, true);
                        }
                    }
                }
            }
        });

        // 创建包含列表和工具栏的面板
        panel = new JPanel(new BorderLayout());
        panel.add(toolBar, BorderLayout.NORTH);
        panel.add(new JScrollPane(fileList), BorderLayout.CENTER);
        panel.setPreferredSize(new Dimension(1000, 200)); // 设置面板的首选大小为宽度300，高度200

    }

    private static class RecentFileCellRenderer extends DefaultListCellRenderer {
        @Override
        public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
            super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);

            if (value instanceof VirtualFile file) {
                setIcon(IconUtil.getIcon(file, 0, null));
                setText("<html><font >" + file.getName() + "</font><font color='gray'>&nbsp;&nbsp;(" + file.getPath() + ")</font></html>");
            }

            return this;
        }
    }

    private static class CustomButtonRenderer extends JButton {
        private final Color originalTextColor;
        private final Color defaultHighlightColor = UIManager.getColor("Button.select");

        public CustomButtonRenderer(String text) {
            super(text);
            setContentAreaFilled(false); // 去除按钮填充
            setBorderPainted(false); // 去除按钮边框
            setFocusPainted(false); // 去除按钮焦点框

            originalTextColor = getForeground(); // 保存按钮文本的原始颜色

            addMouseListener(new MouseAdapter() {
                @Override
                public void mouseEntered(MouseEvent e) {
                    setForeground(defaultHighlightColor); // 设置按钮文本颜色为默认的高亮颜色
                    setCursor(new Cursor(Cursor.HAND_CURSOR)); // 鼠标移入时改变光标样式
                }

                @Override
                public void mouseExited(MouseEvent e) {
                    setForeground(originalTextColor); // 恢复按钮文本颜色为原始颜色
                    setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); // 鼠标移出时恢复光标样式
                }
            });
        }
    }

    public JPanel getPanel() {
        return panel;
    }

    public JComponent getPreferredFocusedComponent() {
        return fileList;
    }

    public Project getProject() {
        return project;
    }

    public void setProject(Project project) {
        this.project = project;
    }

    public void removeAll() {
        properties.removeAllElements(id);
    }

    public void removeSelectedIndices() {
        properties.removeElements(id, fileList.getSelectedIndices());
    }

    public void addFile(VirtualFile file) {
       properties.addFile(id, file);
    }

    public void copyFiles() {
        Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
        Iterator<VirtualFile> iterator = properties.getModel(id).elements().asIterator();
        String copyText = null;
        while (iterator.hasNext()) {
            VirtualFile file = iterator.next();
            copyText = file.getPath() + "\r\n";
        }
        StringSelection stringSelection = new StringSelection(copyText);
        clipboard.setContents(stringSelection, null);
    }

    public void exportFile(Project project, String expToDir) {
        if (StringUtils.isEmpty(expToDir)) {
            return;
        }
        Iterator<VirtualFile> iterator = properties.getModel(id).elements().asIterator();
        try {
            String exportFilePath = properties.getExportFilePath();
            if (StringUtils.isEmpty(exportFilePath)) {
                Messages.showErrorDialog("请配置导出文件路径！", "Error");
                return;
            }
            String tempDir = FileUtil.join(exportFilePath, expToDir);
            FileUtil.deleteRecursively(Path.of(tempDir));
            while (iterator.hasNext()) {
                VirtualFile file = iterator.next();
                String filePath = file.getPath();
                Module module = ModuleUtilCore.findModuleForFile(file, project);
                if (module == null) {
                    Messages.showErrorDialog("未找到文件所属模块：" + filePath, "Error");
                    return;
                }
                String outputPath = getOutputPathForFile(module);
                if (StringUtils.isEmpty(outputPath)) {
                    Messages.showErrorDialog("请配置项目编译路径！", "Error");
                    return;
                }
                if (StringUtils.isBlank(filePath)) {
                    continue;
                }
                String realPath = "";
                String oriPath = getString(filePath, module);

                if (oriPath.endsWith(".class")) {
                    realPath = FileUtil.join(outputPath, oriPath);
                } else {
                    realPath = filePath;
                }
                File fromFile = new File(realPath);
                File toFile = new File(FileUtil.join(tempDir, module.getName(), oriPath));
                if (!fromFile.exists()) {
                    throw new RuntimeException("文件不存在：" + realPath);
                }
                FileUtil.copy(fromFile, toFile);
            }
        } catch (Exception e) {
            Messages.showErrorDialog(e.getMessage(), "Error");
            throw new RuntimeException(e);
        }
    }

    private static @NotNull String getString(String filePath, Module module) {
        String oriPath = "";
        if (filePath.endsWith(".java")) {
            String basePath = module.getProject().getBasePath();
            if (StringUtils.isNotEmpty(basePath)) {
                oriPath = filePath.substring(filePath.indexOf(basePath) + basePath.length() + 1);
                oriPath = oriPath.substring(oriPath.indexOf("/") + 1);
                if (oriPath.indexOf("com/hundsun") > 0) {
                    oriPath = oriPath.substring(oriPath.indexOf("com/hundsun"));
                }
                oriPath = oriPath.substring(0, oriPath.indexOf(".java")) + ".class";
            }
        } else if (filePath.endsWith(".jsp")) {
            if (filePath.indexOf("fui-jsp") > 0) {
                oriPath = filePath.substring(filePath.indexOf("fui-jsp"));
            } else {
                oriPath = filePath.substring(filePath.indexOf(module.getName()) + module.getName().length() + 1);
            }
        } else {
            oriPath = filePath.substring(filePath.indexOf(module.getName()) + module.getName().length() + 1);
        }
        return oriPath;
    }

    public String[] getExpDirAsArray() {
        List<String> history = properties.getHistory();
        if (history == null ||history.isEmpty()) {
            return new String[]{DateUtils.getDate()};
        }
        String[] result = new String[history.size() + 1];
        result[0] = DateUtils.getDate();
        for (int i = 0; i < history.size(); i++) {
            String taskTest = history.get(history.size() - 1 - i);
            TaskInfo taskInfo = noteFileService.parseTaskInfo(taskTest, null);
            String bankName = BankEnum.getBankName(taskInfo.getBankAlias());
            result[i + 1] =  (org.apache.commons.lang.StringUtils.isEmpty(bankName) ? "内部客户" : bankName) + "/#" + taskInfo.getTaskId() + " " + taskInfo.getMessage();
        }
        return result;
    }

    public String getOutputPathForFile(Module module) {
        String outputPath = null;
        if (StringUtils.isEmpty(properties.getBaseClassPath())) {
            CompilerModuleExtension compilerModuleExtension = CompilerModuleExtension.getInstance(module);
            if (compilerModuleExtension != null) {
                VirtualFile output = compilerModuleExtension.getCompilerOutputPath();
                if (output != null) {
                    outputPath = output.getPath();
                }
            }
        } else {
            outputPath = FileUtil.join(properties.getBaseClassPath(), module.getName());
        }
        return outputPath;
    }

    private void importFile(Project project, String inputText) {
        if (StringUtils.isEmpty(inputText)) {
            return;
        }
        String[] split = inputText.split("\\n");
        for (int i = 0; i < split.length; i++) {
            String filePath = split[i].trim();
            if (StringUtils.isEmpty(filePath)) {
                return;
            }

            filePath = filePath.replace("\\Sources\\app", id.substring(0, id.lastIndexOf("/")));
            filePath = filePath.replace("/Sources/app", id.substring(0, id.lastIndexOf("/")));
            if (filePath.contains(" V")) {
                filePath = filePath.substring(0, filePath.indexOf(" V")).trim();
            }
            System.out.println("filePath = " + filePath);
            VirtualFile virtualFile = LocalFileSystem.getInstance().findFileByPath(filePath);
            if (virtualFile == null) {
                continue;
            }
            properties.addFile(id, virtualFile);
        }
    }

}
